import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.io.*;
import java.util.*;

public class ClientManager{
	private static final List<Socket> clients =new ArrayList<Socket>( );

	public void addClient(Socket socket){
		clients.add(socket);
	}

	public void broadcastMsg(String msg){
		synchronized(ClientManager.class ){	 
			Iterator<Socket> iter = clients.iterator();
			while (iter.hasNext()) {
			sendMsg(iter.next(), msg,iter);				
			}			
		}
	}


	private void sendMsg(Socket socket , String msg,Iterator<Socket> iter){
		OutputStreamWriter ost  =null ;
		PrintWriter pw =null ;
		try{
		ost =new OutputStreamWriter(socket.getOutputStream( ),"utf-8");  //客户端关闭之后，容器中的socket还存在，没有释放掉。
		pw = new PrintWriter(ost);
		pw.println(msg);
		pw.flush();	
		}catch(IOException ioe){
			closeIO(ost,pw,socket);	
			iter.remove();   //释放离线的socket
			
			
		}
		
	
	}


	public void closeIO(OutputStreamWriter ost ,PrintWriter pw ,Socket socket){
			try{
			if (null != ost){
				ost.close();
			}
			if (null != pw){
				pw.close();
			}
			if (null != socket) {
				socket.close();				
			}
			}catch(IOException io){

			}

			
			
		
	}





}